#include "widget_funce_control_industrial.h"
#include "ui_widget_funce_control_industrial.h"
#include <QUrl>
#include <QTime>
#include <QNetworkReply>
#include <QMessageBox>
#include <QSlider>
#include <QGraphicsDropShadowEffect>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QNetworkConfigurationManager>
#include <QFormLayout>

Widget_funcE_Control_industrial::Widget_funcE_Control_industrial(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcE_Control_industrial),
    currentSongIndex(-1)  // 初始化当前歌曲索引
{
    ui->setupUi(this);
    // 设置网络配置
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        QNetworkConfiguration config = manager.defaultConfiguration();
        networkSession = new QNetworkSession(config, this);
        networkSession->open();

        connect(networkSession, &QNetworkSession::opened, this, [this](){
            player->setNetworkConfigurations(QList<QNetworkConfiguration>() << networkSession->configuration());
        });
    }

    // 初始化播放器
    player = new QMediaPlayer(this);
    networkManager = new QNetworkAccessManager(this);

    // 设置缓冲监控
    connect(player, &QMediaPlayer::bufferStatusChanged, this, [this](int percent){
        if(percent < 100) {
            ui->lyricLabel->setText(QString("缓冲中...%1%").arg(percent));
        } else {
            ui->lyricLabel->setText("准备播放");
        }
    });

    // 设置窗口样式
    this->setStyleSheet(R"(
        QWidget {
            background-color: #f0f2f5;
            font-family: "Microsoft YaHei";
        }

        /* 主容器样式 */
        #Widget_funcE_Control_industrial {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                          stop:#2C3E50, stop:1 #4A69BB);
            border-radius: 15px;
            padding: 15px;
        }

        /* 按钮通用样式 */
        QPushButton:not(#playButton):not(#pauseButton):not(#stopButton):not(#prevButton):not(#nextButton) {
                background-color: rgba(129, 212, 250, 0.7) !important;
                border: 1px solid rgba(79, 195, 247, 0.5) !important;
                border-radius: 8px !important;
                color: #2C3E50 !important;
                padding: 8px 15px !important;
                min-width: 80px !important;
            }

            QPushButton:not(#playButton):not(#pauseButton):not(#stopButton):not(#prevButton):not(#nextButton):hover {
                background-color: rgba(79, 195, 247, 0.8) !important;
            }

            QPushButton:not(#playButton):not(#pauseButton):not(#stopButton):not(#prevButton):not(#nextButton):pressed {
                background-color: rgba(3, 169, 244, 0.6) !important;
            }

        /* 播放控制按钮特殊样式 */
        #playButton, #pauseButton, #stopButton, #prevButton, #nextButton {
            min-width: 40px !important;
            max-width: 50px !important;
            border-radius: 20px !important;
            font-size: 15px !important;
            background-color: rgba(3, 169, 244, 0.8) !important;
            color: white !important;
        }

        /* 搜索框样式 */
        #searchEdit {
            background-color: rgba(255, 236, 204, 0.9) !important;
            border: 1px solid rgba(255, 193, 7, 0.3) !important;
            border-radius: 12px !important;
            padding: 5px 10px !important;
            font-size: 14px !important;
            color: #E65100 !important;
        }

        /* 下拉框样式 */
        #searchTypeCombo {
            background-color: rgba(250, 231, 228, 0.9) !important;
            border: 1px solid rgba(124, 179, 66, 0.3) !important;
            border-radius: 12px !important;
            padding: 5px 10px !important;
            min-width: 80px !important;
            color: #2E7D32 !important;
        }
        #searchTypeCombo::drop-down
        {
            border-left: 1px solid rgba(124, 179, 66, 0.3) !important;
        }

        /* 歌曲列表样式 */
        #songList {
            background-color: rgba(243, 235, 255, 0.95) !important;
            border: 1px solid rgba(156, 39, 176, 0.2) !important;
            border-radius: 10px !important;
            padding: 5px !important;
            font-size: 14px !important;
        }

        #songList::item {
            padding: 8px 10px !important;
            border-bottom: 1px solid rgba(156, 39, 176, 0.1) !important;
            color: #4A148C !important;
        }

        #songList::item:hover {
             background-color: rgba(221, 187, 255, 0.5) !important;
        }

        #songList::item:selected {
        background-color: rgba(186, 104, 200, 0.4) !important;
        color: #6A1B9A !important;              /* 选中时的文字颜色 */
        }

        /* 进度条和音量条样式 */
        #progressSlider::groove:horizontal, #volumeSlider::groove:horizontal {
                height: 6px !important;
                background: rgba(224, 211, 255, 0.7) !important;
                border-radius: 3px !important;
            }

            #progressSlider::handle:horizontal, #volumeSlider::handle:horizontal {
                width: 14px !important;
                height: 14px !important;
                margin: -4px 0 !important;
                background: #9C27B0 !important;
                border-radius: 7px !important;
            }

            #progressSlider::sub-page:horizontal, #volumeSlider::sub-page:horizontal {
                background: #7B1FA2 !important;
                border-radius: 3px !important;
            }

        /* 时间和音量标签样式 */
        #currentTimeLabel, #totalTimeLabel, #volumeLabel {
            color: #4A148C !important;
            font-size: 12px !important;
            min-width: 40px !important;
            font-weight: 500 !important;
        }

        /* 当前歌曲标签 */
        #currentSongLabel {
            color: #E65100 !important;
            font-size: 16px !important;
            font-weight: bold !important;
            qproperty-alignment: AlignCenter !important;  //居中
            background-color: rgba(255, 245, 230, 0.3) !important;
            padding: 5px !important;
            border-radius: 8px !important;
        }

        /* 歌词标签 */
       #lyricLabel {
       color: #00695C !important;                /* 白色文字 */
       font-size: 16px !important;             /* 较大字号 */
       font-weight: bold !important;           /* 粗体 */
       qproperty-alignment: AlignCenter !important; /* 居中 */
       background: rgba(222, 249, 245, 0.6) !important; /* 半透明黑色背景 */
       border-radius: 10px !important;         /* 圆角 */
       padding: 15px !important;               /* 内边距 */
       min-height: 60px !important;            /* 最小高度 */
       border: 1px solid rgba(0, 150, 136, 0.2) !important;
          }
    )");

    // 设置窗口属性
    this->setWindowTitle("音乐播放器");
    this->setWindowIcon(QIcon(":/音乐")); // 需要添加资源文件
    this->setFixedSize(600, 550);  // 增加高度以容纳音量控件

    // 初始化进度条
    ui->progressSlider->setPageStep(1000); // 设置步进
    ui->progressSlider->setTracking(true); // 实时更新
    ui->progressSlider->setRange(0, 100);

    // 初始化音量滑块
    ui->volumeSlider->setRange(0, 100);
    ui->volumeSlider->setValue(80);  // 默认音量80%
    player->setVolume(80);           // 设置初始音量
    ui->volumeLabel->setText("音量: 80%");

    // 连接信号槽
    connect(player, &QMediaPlayer::positionChanged, this, &Widget_funcE_Control_industrial::updateProgress);
    connect(player, &QMediaPlayer::durationChanged, this, &Widget_funcE_Control_industrial::updateDuration);
    connect(player, &QMediaPlayer::stateChanged, this, &Widget_funcE_Control_industrial::handleSongFinished);
    connect(player, &QMediaPlayer::mediaStatusChanged, this, &Widget_funcE_Control_industrial::handleMediaStatusChanged);
    connect(ui->searchEdit, &QLineEdit::returnPressed, ui->searchButton, &QPushButton::click);
    connect(player, &QMediaPlayer::positionChanged, this, &Widget_funcE_Control_industrial::displayCurrentLyric);

    // 连接上一首、下一首和音量控制信号
    connect(ui->prevButton, &QPushButton::clicked, this, &Widget_funcE_Control_industrial::onPrevButtonClicked);
    connect(ui->nextButton, &QPushButton::clicked, this, &Widget_funcE_Control_industrial::onNextButtonClicked);
    connect(ui->volumeSlider, &QSlider::valueChanged, this, &Widget_funcE_Control_industrial::onVolumeChanged);
}

Widget_funcE_Control_industrial::~Widget_funcE_Control_industrial()
{
    delete ui;
    delete player;
    delete networkManager;
}

// 自动连接槽函数实现
void Widget_funcE_Control_industrial::on_playButton_clicked()
{
    if (player->mediaStatus() == QMediaPlayer::NoMedia && !searchResults.isEmpty()) {
        playSongByIndex(0); // 如果没有媒体且有歌曲列表，播放第一首
    } else {
        player->play();
    }
}

void Widget_funcE_Control_industrial::on_pauseButton_clicked() { player->pause(); }
void Widget_funcE_Control_industrial::on_stopButton_clicked() { player->stop(); }

// 上一首按钮点击事件
void Widget_funcE_Control_industrial::onPrevButtonClicked()
{
    if (searchResults.isEmpty()) {
        QMessageBox::information(this, "提示", "没有歌曲可播放");
        return;
    }

    // 计算上一首索引（循环播放）
    int prevIndex = (currentSongIndex - 1 + searchResults.size()) % searchResults.size();
    playSongByIndex(prevIndex);
}

// 下一首按钮点击事件
void Widget_funcE_Control_industrial::onNextButtonClicked()
{
    if (searchResults.isEmpty()) {
        QMessageBox::information(this, "提示", "没有歌曲可播放");
        return;
    }

    // 计算下一首索引（循环播放）
    int nextIndex = (currentSongIndex + 1) % searchResults.size();
    playSongByIndex(nextIndex);
}

// 音量调节事件
void Widget_funcE_Control_industrial::onVolumeChanged(int value)
{
    if (player) {
        player->setVolume(value);
        ui->volumeLabel->setText(QString("音量: %1%").arg(value));
    }
}

// 进度条平滑移动
void Widget_funcE_Control_industrial::on_progressSlider_sliderMoved(int position)
{
    // 防止频繁跳转
    static qint64 lastPos = 0;
    if(qAbs(position - lastPos) > 1000) { // 只有变化超过1秒才跳转
        player->setPosition(position);
        lastPos = position;
    }
}

// 媒体状态处理
void Widget_funcE_Control_industrial::handleSongFinished(QMediaPlayer::State state)
{
    if(state == QMediaPlayer::StoppedState) {
        ui->currentTimeLabel->setText("00:00");
        ui->progressSlider->setValue(0);
        ui->lyricLabel->setText("播放停止");
    }
    else if(state == QMediaPlayer::PlayingState) {
        if (lyricMap.isEmpty()) {
            ui->lyricLabel->setText("正在播放...");
        }
    }
}

// 媒体状态变化处理（用于自动播放下一首）
void Widget_funcE_Control_industrial::handleMediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    // 当当前媒体播放结束且有下一首时自动播放下一首
    if (status == QMediaPlayer::EndOfMedia && !searchResults.isEmpty()) {
        onNextButtonClicked();
    }
}

// 搜索功能点击
void Widget_funcE_Control_industrial::on_searchButton_clicked()
{
    QString keyword = ui->searchEdit->text().trimmed();

    if(!keyword.isEmpty())
    {
        ui->searchButton->setEnabled(false);
        ui->searchButton->setText("搜索中...");
        ui->songList->clear();

        QListWidgetItem *loadingItem = new QListWidgetItem("正在搜索...");
        loadingItem->setTextAlignment(Qt::AlignCenter);
        ui->songList->addItem(loadingItem);
        searchMusic(keyword);
    }
}

// 处理歌曲列表项的双击事件
void Widget_funcE_Control_industrial::on_songList_itemDoubleClicked(QListWidgetItem *item)
{
    // 从列表项的自定义数据中获取歌曲/艺术家的唯一标识ID
    QString id = item->data(Qt::UserRole).toString();
    QString type = item->data(Qt::UserRole+1).toString();

    if(type == "artist") {
        fetchArtistSongs(id);
    } else {
        // 查找双击的歌曲在列表中的索引
        for (int i = 0; i < searchResults.size(); ++i) {
            if (searchResults[i].second == id) {
                currentSongIndex = i;
                break;
            }
        }
        playMusicById(id);
        fetchLyric(id);
        ui->songList->setCurrentItem(item); // 高亮显示当前项
    }
}

// 按索引播放歌曲
void Widget_funcE_Control_industrial::playSongByIndex(int index)
{
    if (index < 0 || index >= searchResults.size()) return;

    currentSongIndex = index;
    QString songId = searchResults[index].second;
    QString songName = searchResults[index].first;

    // 播放歌曲
    playMusicById(songId);
    fetchLyric(songId);

    // 更新UI
    ui->currentSongLabel->setText("正在播放: " + songName);

    // 高亮显示当前播放的歌曲
    if (ui->songList->count() > index) {
        ui->songList->setCurrentRow(index);
    }
}

// 时间显示
void Widget_funcE_Control_industrial::updateProgress(qint64 position)
{
    if(!ui->progressSlider->isSliderDown()) {
        ui->progressSlider->setValue(position);
    }

    // 修正时间显示格式（处理超过60分钟的情况）
    QTime currentTime(0, 0);
    currentTime = currentTime.addMSecs(position);
    QString format = currentTime.hour() > 0 ? "hh:mm:ss" : "mm:ss";
    ui->currentTimeLabel->setText(currentTime.toString(format));

    displayCurrentLyric(position);
}

void Widget_funcE_Control_industrial::updateDuration(qint64 duration)
{
    ui->progressSlider->setRange(0, duration);

    QTime totalTime(0, 0);
    totalTime = totalTime.addMSecs(duration);
    QString format = totalTime.hour() > 0 ? "hh:mm:ss" : "mm:ss";
    ui->totalTimeLabel->setText(totalTime.toString(format));
}

// 搜索音乐
void Widget_funcE_Control_industrial::searchMusic(const QString &keyword)
{
    int searchType = ui->searchTypeCombo->currentIndex();
    QString url;

    if(searchType == 0) {
        url = QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10")
              .arg(keyword);
    } else {
        url = QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=100&offset=0&total=true&limit=10")
              .arg(keyword);
    }

    // 发送get请求
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("Referer", "http://music.163.com/");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

    QNetworkReply *reply = networkManager->get(request);

    QTimer *timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, &QTimer::timeout, [reply]() {
        if(reply->isRunning()) reply->abort();
    });
    timer->start(10000);
    replyTimeouts.insert(reply, timer);

    connect(reply, &QNetworkReply::finished, [this, reply]() {
        if(replyTimeouts.contains(reply)) {
            replyTimeouts[reply]->deleteLater();
            replyTimeouts.remove(reply);
        }
        handleSearchReply(reply);
    });
}

void Widget_funcE_Control_industrial::playMusicById(const QString &id)
{
    // 先停止当前播放并断开所有连接
    player->stop();
    player->disconnect(this);

    // 根据歌曲id构建播放地址
    QString url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id);

    // 设置媒体内容
    player->setMedia(QUrl(url));

    // 重新连接必要的信号
    connect(player, &QMediaPlayer::positionChanged, this, &Widget_funcE_Control_industrial::updateProgress);
    connect(player, &QMediaPlayer::durationChanged, this, &Widget_funcE_Control_industrial::updateDuration);
    connect(player, &QMediaPlayer::stateChanged, this, &Widget_funcE_Control_industrial::handleSongFinished);
    connect(player, &QMediaPlayer::mediaStatusChanged, this, &Widget_funcE_Control_industrial::handleMediaStatusChanged);

    // 缓冲状态监控
    connect(player, &QMediaPlayer::bufferStatusChanged, this, [this](int percent){
        if(percent < 100) {
            ui->lyricLabel->setText(QString("缓冲中...%1%").arg(percent));
        } else {
            ui->lyricLabel->setText("准备播放");
        }
    });

    // 错误处理
    connect(player, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error),
            [this](QMediaPlayer::Error error){
        ui->lyricLabel->setText("播放错误: " + player->errorString());
    });

    // 延迟播放，等待缓冲
    QTimer::singleShot(2000, [this](){
        player->play();
    });
}

void Widget_funcE_Control_industrial::fetchLyric(const QString &id)
{
    // 断开之前的缓冲信号连接
    disconnect(player, &QMediaPlayer::bufferStatusChanged, this, nullptr);

    QString url = QString("https://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(id);

    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("Referer", "http://music.163.com/");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

    QNetworkReply *reply = networkManager->get(request);

    QTimer *timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, &QTimer::timeout, [reply]() {
        if(reply->isRunning()) reply->abort();
    });
    timer->start(5000); // 5秒超时
    replyTimeouts.insert(reply, timer);

    connect(reply, &QNetworkReply::finished, [this, reply]() {
        if(replyTimeouts.contains(reply)) {
            replyTimeouts[reply]->deleteLater();
            replyTimeouts.remove(reply);
        }
        handleLyricReply(reply);
    });
}

// 获取指定歌手的歌曲列表
void Widget_funcE_Control_industrial::fetchArtistSongs(const QString &artistId)
{
    // 构建请求URL，使用艺术家ID拼接网易云音乐API地址
    QString url = QString("http://music.163.com/api/artist/%1").arg(artistId);

    // 设置网络请求
    QNetworkRequest request;
    request.setUrl(QUrl(url)); // 设置请求URL

    // 添加必要的HTTP头部信息，模拟浏览器请求以避免被服务器拒绝
    request.setRawHeader("Referer", "http://music.163.com/"); // 设置来源页
    request.setRawHeader("User-Agent",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); // 设置用户代理

    // 发起GET请求
    QNetworkReply *reply = networkManager->get(request);

    // 设置请求超时定时器（10秒）
    QTimer *timer = new QTimer(this);
    timer->setSingleShot(true); // 单次触发定时器
    connect(timer, &QTimer::timeout, [reply]() {
        // 如果请求仍在进行，则中止请求
        if(reply->isRunning()) reply->abort();
    });
    timer->start(10000); // 10秒超时

    // 将回复和定时器关联存储，用于后续清理
    replyTimeouts.insert(reply, timer);

    // 请求完成时的处理
    connect(reply, &QNetworkReply::finished, [this, reply]() {
        // 清理超时定时器
        if(replyTimeouts.contains(reply)) {
            replyTimeouts[reply]->deleteLater(); // 延迟删除定时器
            replyTimeouts.remove(reply); // 从映射表中移除
        }

        // 处理API返回的数据
        handleArtistSongsReply(reply);
    });
}

// 歌词显示
void Widget_funcE_Control_industrial::displayCurrentLyric(qint64 position)
{
    if(lyricMap.isEmpty()) {
        ui->lyricLabel->setText("暂无歌词");
        return;
    }

    // 找到第一个大于等于当前时间的位置
    auto it = lyricMap.lowerBound(position);

    // 如果没找到（超过最后一句），显示最后一句
    if(it == lyricMap.end()) {
        --it;
        ui->lyricLabel->setText(it.value());
        return;
    }

    // 如果是第一句或找到精确匹配，直接显示
    if(it == lyricMap.begin() || it.key() == position) {
        ui->lyricLabel->setText(it.value());
        return;
    }

    // 否则显示前一句歌词
    --it;
    ui->lyricLabel->setText(it.value());
}

void Widget_funcE_Control_industrial::handleSearchReply(QNetworkReply *reply)
{
    ui->searchButton->setEnabled(true);
    ui->searchButton->setText("搜索");

    if(reply->error() != QNetworkReply::NoError) {
        QMessageBox::warning(this, "错误", "搜索失败: " + reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonObject obj = doc.object();

    ui->songList->clear();
    searchResults.clear();
    currentSongIndex = -1;  // 重置当前索引

    int searchType = ui->searchTypeCombo->currentIndex();
    if(searchType == 0) {
        QJsonArray songs = obj.value("result").toObject().value("songs").toArray();
        for(const QJsonValue &value : songs) {
            QJsonObject song = value.toObject();
            QString name = song.value("name").toString();
            QString id = QString::number(song.value("id").toInt());

            QJsonArray artists = song.value("artists").toArray();
            QStringList artistNames;
            for(const QJsonValue &artistValue : artists) {
                artistNames << artistValue.toObject().value("name").toString();
            }

            QListWidgetItem *item = new QListWidgetItem(QString("%1 - %2").arg(name).arg(artistNames.join("/")));
            item->setData(Qt::UserRole, id);
            ui->songList->addItem(item);

            searchResults.append(qMakePair(name, id));
        }
    } else {
        QJsonArray artists = obj.value("result").toObject().value("artists").toArray();
        for(const QJsonValue &value : artists) {
            QJsonObject artist = value.toObject();
            QString name = artist.value("name").toString();
            QString id = QString::number(artist.value("id").toInt());

            QListWidgetItem *item = new QListWidgetItem(name);
            item->setData(Qt::UserRole, id);
            item->setData(Qt::UserRole+1, "artist");
            ui->songList->addItem(item);
        }
    }

    if(ui->songList->count() == 0) {
        QListWidgetItem *item = new QListWidgetItem("未找到结果");
        item->setTextAlignment(Qt::AlignCenter);
        ui->songList->addItem(item);
    }

    reply->deleteLater();
}

// 歌词请求
void Widget_funcE_Control_industrial::handleLyricReply(QNetworkReply *reply)
{
    if(reply->error() != QNetworkReply::NoError) {
        ui->lyricLabel->setText("歌词加载失败: " + reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);

    if(doc.isNull()) {
        ui->lyricLabel->setText("歌词解析失败");
        reply->deleteLater();
        return;
    }

    QJsonObject obj = doc.object();
    if(!obj.contains("lrc")) {
        // 获取详细的错误信息
        QString errorDetail = "暂无歌词";

        if(obj.contains("code")) {
            int errorCode = obj["code"].toInt();
            QString errorMsg = obj.contains("msg") ? obj["msg"].toString() : "";

            switch(errorCode) {
                case 200:
                    errorDetail = "纯音乐，无歌词";
                    break;
                case 404:
                    errorDetail = "歌曲不存在";
                    break;
                case 301:
                    errorDetail = "需要VIP权限";
                    break;
                default:
                    errorDetail = QString("错误代码: %1 %2").arg(errorCode).arg(errorMsg);
                    break;
            }
        }

        ui->lyricLabel->setText(errorDetail);
        qDebug() << "歌词API响应(无lrc字段):" << obj;
        reply->deleteLater();
        return;
    }

    QString lyricText = obj["lrc"].toObject()["lyric"].toString();
    if(lyricText.isEmpty()) {
        ui->lyricLabel->setText("空白歌词");
    } else {
        parseLyric(lyricText);
        if (!lyricMap.isEmpty()) {
            ui->lyricLabel->setText(lyricMap.first());
        } else {
            ui->lyricLabel->setText("歌词解析失败");
        }
    }

    reply->deleteLater();
}

void Widget_funcE_Control_industrial::handleArtistSongsReply(QNetworkReply *reply)
{
    // 检查网络错误
    if(reply->error() != QNetworkReply::NoError) {
        QMessageBox::warning(this, "错误", "获取歌手歌曲失败: " + reply->errorString());
        reply->deleteLater();  // 释放reply对象
        return;
    }

    // 读取返回的所有数据
    QByteArray data = reply->readAll();

    // 解析JSON数据
    QJsonDocument doc = QJsonDocument::fromJson(data);  // 将字节数组转换为JSON文档
    QJsonObject obj = doc.object();  // 获取JSON对象
    QJsonArray hotSongs = obj.value("hotSongs").toArray();  // 获取热门歌曲数组

    // 清空UI列表和搜索结果
    ui->songList->clear();
    searchResults.clear();
    currentSongIndex = -1;  // 重置当前索引

    // 遍历所有热门歌曲
    for(const QJsonValue &value : hotSongs) {
        QJsonObject song = value.toObject();  // 获取单首歌曲对象

        // 获取歌曲基本信息
        QString name = song.value("name").toString();  // 歌曲名称
        QString id = QString::number(song.value("id").toInt());  // 歌曲ID

        // 获取歌手信息
        QJsonArray artists = song.value("ar").toArray();  // 歌手数组
        QStringList artistNames;  // 存储所有歌手名称
        for(const QJsonValue &artistValue : artists) {
            artistNames << artistValue.toObject().value("name").toString();  // 添加歌手名称
        }

        // 创建列表项并添加到UI
        QListWidgetItem *item = new QListWidgetItem(
            QString("%1 - %2").arg(name).arg(artistNames.join("/")));  // 格式: 歌曲名 - 歌手1/歌手2
        item->setData(Qt::UserRole, id);  // 将歌曲ID存储为项的用户数据
        ui->songList->addItem(item);  // 添加到列表控件

        // 添加到搜索结果缓存
        searchResults.append(qMakePair(name, id));
    }

    // 释放reply对象
    reply->deleteLater();
}

// 歌词解析函数
void Widget_funcE_Control_industrial::parseLyric(const QString &lyricText) {
    lyricMap.clear();
    if (lyricText.isEmpty()) return;

    // 支持 [mm:ss]、[mm:ss.xx]、[mm:ss:xx] 三种格式
    QRegExp rx("\\[(\\d+):(\\d+)(?:[.:](\\d{1,3}))?\\]");
    rx.setMinimal(true);
    QStringList lines = lyricText.split('\n');

    for (const QString &line : lines) {
        if (line.startsWith("[ti:") || line.startsWith("[ar:") || line.startsWith("[al:")) {
            continue; // 跳过元数据行
        }

        int pos = 0;
        while ((pos = rx.indexIn(line, pos)) != -1) {
            int min = rx.cap(1).toInt();
            int sec = rx.cap(2).toInt();
            QString msecStr = rx.cap(3); // 可能为空、1-3位数字

            // 处理毫秒：空→0，1位→*100，2位→*10，3位→直接用
            int msec = 0;
            if (!msecStr.isEmpty()) {
                msec = msecStr.toInt();
                if (msecStr.length() == 1) msec *= 100;
                else if (msecStr.length() == 2) msec *= 10;
            }

            qint64 time = min * 60000 + sec * 1000 + msec;
            QString text = line.mid(pos + rx.matchedLength()).trimmed();

            if (!text.isEmpty()) {
                lyricMap.insert(time, text);
            }
            pos += rx.matchedLength();
        }
    }
    qDebug() << "[解析完成] 歌词总数:" << lyricMap.size(); // 验证解析结果
}
